package com.harboursoftware.xstorage.operations;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ListMultimap;
import com.harboursoftware.xstorage.XStorageException;
import com.harboursoftware.xstorage.ac.AccessControlPolicy;
import com.harboursoftware.xstorage.ac.Permission;
import com.harboursoftware.xstorage.fs.BucketNotExistException;
import com.harboursoftware.xstorage.model.XBucket;
import com.harboursoftware.xstorage.model.XElement;
import com.harboursoftware.xstorage.model.XUser;
import com.harboursoftware.xstorage.results.EmptyContentResult;
import com.harboursoftware.xstorage.results.ErrorResult;
import com.harboursoftware.xstorage.results.Result;

public class PutBucketAcl extends Operation {
    private final static Logger log = LoggerFactory.getLogger(PutBucketAcl.class);

    @Override
    public Result execute(XUser requester, XElement element, ListMultimap<String, String> headers,
        Map<String, String> parameters) {
        XBucket bucket = (XBucket) element;
        try {
            //TODO: 是否需要校验合法性，比如acl中的用户不存在，acl中的email不合法，acl中的email不存在
            //acl中group错误,
            //TODO:owner是否可以改变，owner错误时如何处理
            XBucket persistedBucket = new XBucket(bucket.getName());
            fileSystem.loadBucketACP(persistedBucket);
            AccessControlPolicy acp = persistedBucket.getAcp();
            if (!acp.checkPermission(requester, getRequiredPermission())) {
                return ErrorResult.create(ErrorResult.Type.ACCESS_DENIED);
            }
            fileSystem.putBucketAcp(bucket);
            return new EmptyContentResult();
        } catch (BucketNotExistException e) {
            return ErrorResult.createNoSuckBucket(bucket.getName());
        } catch (XStorageException e) {
            log.error("error occured when put bucket acl", e);
            return ErrorResult.create(ErrorResult.Type.INTERNAL_ERROR);
        }
    }

    @Override
    public Permission getRequiredPermission() {
        return Permission.WRITE_ACP;
    }
}
